package com.shujia.zookeeper;

import org.apache.hadoop.fs.Path;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

public class Code06DeleteAll {
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = new ZooKeeper("master:2181",
                15 * 1000,
                new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        System.out.println("process函数执行了...");
                    }
                }
        );

        String path = "/api";
        deleteAll(zooKeeper, path, path);

        zooKeeper.close();
    }


    public static void deleteAll(ZooKeeper zooKeeper, String path, String flagPath) throws InterruptedException, KeeperException {

        Stat exists = zooKeeper.exists(path, false);
        if (exists != null) {
            if (exists.getNumChildren() == 0) {
                // 如果节点存在，并且没有子节点 那么可以直接删除

                zooKeeper.delete(path, -1);
                System.out.println(path + "路径已删除..");
                String parentPath = new Path(path).getParent().toString();
                // 如果父路径和一开始要删除的路径不相同，那么就需要删除
                if (!parentPath.equals(flagPath)) {
                    deleteAll(zooKeeper, parentPath, flagPath);
                } else {
                    System.out.println("已经遍历到一开始的父路径");
                    if (zooKeeper.exists(parentPath, false).getNumChildren() == 0) {
                        // 如果遍历的父路径是为空，那么可以直接删除
                        zooKeeper.delete(parentPath, -1);
                        System.out.println(parentPath + "路径已删除..");
                    }
                }
            } else {
                // 存在有子节点，那么需要获取子节点
                List<String> children = zooKeeper.getChildren(path, false);
                // 获取子节点的名称
                for (String child : children) {
                    // 需要拼接子节点路径
                    String childPath = path + "/" + child;
                    // 对于获取到的子节点，那么再去判断是否有子节点，这时可以调用自身
                    deleteAll(zooKeeper, childPath, flagPath);
                }
            }


        } else {
            System.out.println(path + "节点不存在...");
        }

    }


}
